package com.point.business.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.point.business.database.managers.ScheduleManager;
import com.point.business.database.model.Schedule;
import com.point.business.util.UTFUtil;

/**
 * Servlet implementation class LoginServlet
 */

public class AllActiveNotificationByUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AllActiveNotificationByUserServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		UTFUtil.utf8(request, response);
		PrintWriter out = response.getWriter();
		int userId = -1;
		if (request.getParameter("userId") != null) {
			userId = Integer.parseInt(request.getParameter("userId"));
		} else {
			userId = (Integer) request.getAttribute("userId");
		}
		String type = request.getParameter("type");
		JsonObject jsono = new JsonObject();
		List<Schedule> allSchedules = null;
		if(type.equals("")){
			allSchedules = ScheduleManager.getInstance().getSchedulesForUserForAllTypes(userId);
		}else{
			allSchedules = ScheduleManager.getInstance().getAllSchedulesByUser(type, userId);
		}
		

		if (!allSchedules.isEmpty()) {
			JsonArray jsona = new JsonArray();
			
			
			for (Schedule schedule : allSchedules) {
				JsonObject jsonoList = new JsonObject();
				if(schedule.isActive()){
					jsonoList.addProperty("active", "активна");
				}else{
					jsonoList.addProperty("active", "испратена порака");
				}
				SimpleDateFormat date = new SimpleDateFormat("dd.MM.yyyy");
				jsonoList.addProperty("searchDate", date.format(schedule.getSearchDate()).toString());
				jsonoList.addProperty("notification", schedule.getSearchedFor(schedule.getSearchQuery()));
				jsonoList.addProperty("id", schedule.getId());
				jsona.add(jsonoList);
				
			}
			/*Gson gson = new GsonBuilder().setPrettyPrinting().create();
			String json = gson.toJson(allSchedules);
			byte[] utf8JsonString = json.getBytes("UTF8");
			String str = new String(utf8JsonString, "UTF-8");*/
			out.print(jsona);
		} else {
			jsono.addProperty("errorMsg", "Немате активни нотификации");
			out.print(jsono);
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
}
